package com.int_tech.car.controller;

import com.int_tech.car.dao.*;
import com.int_tech.car.entity.*;
import com.int_tech.car.service.CarService;
import com.int_tech.mession.dao.MessionDao;
import com.int_tech.mession.entity.Mession;
import com.int_tech.rate.controller.RateController;
import com.int_tech.station.dao.StationDao;
import com.int_tech.station.entity.Station;
import com.int_tech.station.service.StationService;
import com.int_tech.user.dao.UserDao;
import com.int_tech.user.entity.User;
import com.int_tech.utils.*;
import com.int_tech.utils.poi.ReadExcelCar;
import com.int_tech.utils.poi.ReadExcelCarCeiling;
import com.int_tech.utils.poiOut.CarPoi;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.hibernate.mapping.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.smartcardio.Card;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.UnknownHostException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("car")
public class CarController {

    @Autowired
    private UserDao userDao;

    @Autowired
    private CarInfoDao carInfoDao;

    @Autowired
    private CarOpenInfoDao carOpenInfoDao;

    @Autowired
    private CarService carService;

    @Autowired
    private StationService stationService;

    @Autowired
    private StationDao stationDao;

    @Autowired
    private CarInfoDataDao carInfoDataDao;

    @Autowired
    private MessionDao messionDao;

    @Autowired
    private CityDao cityDao;

    @Autowired
    private CarDao carDao;

    /**
     * 车辆管理，根据id车辆信息，在根据车辆id得到车辆信息
     */
    @RequestMapping(value = "/ByIdCar", method = RequestMethod.GET)
    public String allStation(Model model, HttpServletRequest request) {
        int clientId = (int) request.getSession().getAttribute("uid");
        User user = userDao.findOne(clientId);
        List<Station> stationByid = (List<Station>) stationService.findStationByClientId(clientId).getData();
        model.addAttribute("AllStation", stationByid);
        model.addAttribute("AllStationSize", stationByid.size());
        if (user.getType() == 1) {
            List<Car> list = (List<Car>) carService.findAllCar().getData();
            model.addAttribute("AllCar", list);
            return "/car/car";
        }
        List<Car> carList = (List<Car>) carService.findCarByClientId(clientId).getData();
        model.addAttribute("AllCar", carList);
        return "/car/car";
    }


    /**
     * 车辆管理，添加车辆信息
     */
    @ResponseBody
    @RequestMapping(value = "/addCar", method = RequestMethod.POST)
    public String addStation(Car car, HttpServletRequest request) {
        String a = "";
        try {
            int clientId = (int) request.getSession().getAttribute("uid");
            String carNumber = car.getCarNumber();
            if (carNumber == null) {
                a = "4";
            }
            String substring = carNumber.substring(0, 1);
            if (substring.equals("0")) {
                car.setCarNumber(carNumber);
                String substring1 = carNumber.substring(0, 3);
                City city = cityDao.findByCityNumber(substring1);
                if (city == null) {
                    a = "3";
                }
                String substring2 = carNumber.substring(3, carNumber.length());
                String carCnumber = city.getCity() + substring2;
                car.setCarCnumber(carCnumber);
            } else if (!substring.equals("0")) {
                car.setCarCnumber(carNumber);
                String substring1 = carNumber.substring(0, 1);
                City city = cityDao.findByCity(substring1);
                if (city == null) {
                    a = "3";
                }
                String substring2 = carNumber.substring(1, carNumber.length());
                String carCnumber = city.getCityNumber() + substring2;
                car.setCarNumber(carCnumber);
            }
            car.setClientId(clientId);
            car.setCreateTime(new Date());
            car.setUpdateTime(new Date());
            Car save = carDao.save(car);
            if (save != null) {
                a = "0";
            } else {
                a = "1";
            }
            return a;
        } catch (Exception e) {
            e.printStackTrace();
            return "2";
        }
    }


    /**
     * 车辆管理，删除车站信息
     */
    @RequestMapping(value = "/deleteCar", method = RequestMethod.POST)
    @ResponseBody
    public String deleteStation(String order, HttpServletRequest request) {
        int clientId = (int) request.getSession().getAttribute("uid");
        User user = userDao.findOne(clientId);
        Integer id = Integer.valueOf(order);
        if (user.getType() == 1) {
            return "2";
        }
        else if(user.getType() == 3)
        {
            return  "2";
        }
        Car one = carDao.findOne(id);
        one.setUpdateTime(new Date());
        one.setIsDel(CarEnum.OFF.getCode());
        Car save = carDao.save(one);
        String a = "";
        if (save != null) {
            a = "0";
        } else {
            a = "1";
        }
        return a;
    }


    /**
     * 车辆管理，修改车辆信息
     */
    @RequestMapping(value = "/updateCar", method = RequestMethod.POST)
    @ResponseBody
    public Result updateStation(Car car, HttpServletRequest request) {
        int clientId = (int) request.getSession().getAttribute("uid");
        String carNumber = car.getCarNumber();
        if (carNumber == null) {
            return Result.build(500, "车牌号不能为空");
        }
        String substring = carNumber.substring(0, 1);
        if (substring.equals("0")) {
            car.setCarNumber(carNumber);
            String substring1 = carNumber.substring(0, 3);
            City city = cityDao.findByCityNumber(substring1);
            if (city == null) {
                return Result.build(500, "车牌号有误!");
            }
            String substring2 = carNumber.substring(3, carNumber.length());
            String carCnumber = city.getCity() + substring2;
            car.setCarCnumber(carCnumber);
        } else if (!substring.equals("0")) {
            car.setCarCnumber(carNumber);
            String substring1 = carNumber.substring(0, 1);
            City city = cityDao.findByCity(substring1);
            if (city == null) {
                return Result.build(500, "车牌号有误!");
            }
            String substring2 = carNumber.substring(1, carNumber.length());
            String carCnumber = city.getCityNumber() + substring2;
            car.setCarNumber(carCnumber);
        }
        car.setClientId(clientId);
        Result result = carService.updateCar(car);
        return result;
    }

    /**
     * 通过场站信息查询车辆列表
     *
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     * @throws UnknownHostException
     */
    @RequestMapping(value = "/getCarListByStationId", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String getCarListByStationId(HttpServletRequest request, String stationId) throws UnsupportedEncodingException, UnknownHostException {

        int id = Integer.parseInt(stationId);

        List<Car> cars = (List<Car>) carService.findCarByStationId(id).getData();

        String msg = "";

        for (Car car : cars) {
            msg += "<li class='p-bt-10 car' name='" + car.getCarNumber() + "'>" + car.getCarCnumber() + "</li>";
        }

        JSONObject object = new JSONObject();
        object.put("status", "success");
        object.put("cars", cars);
        object.put("msg", msg);

        return object.toString();
    }

    /**
     * 车辆管理，搜索接口
     */
    @RequestMapping(value = "/souSuoCar")
    public String chooseStationName(HttpServletRequest request, Model model, String word) {
        List<Car> carWordList = new ArrayList<>();
        int clientId = (int) request.getSession().getAttribute("uid");
        User user = userDao.findOne(clientId);
        if (user.getType() == 1) {
            List<Car> list = (List<Car>) carService.findAllCar().getData();
            for (Car ca : list) {
                if (ca.toString().contains(word)) {
                    carWordList.add(ca);
                }
            }
            model.addAttribute("AllCar", carWordList);
            return "/car/car";
        }
        List<Car> carList = (List<Car>) carService.findCarByClientId(clientId).getData();
        for (Car ca : carList) {
            if (ca.toString().contains(word)) {
                carWordList.add(ca);
            }
        }
        model.addAttribute("AllCar", carWordList);
        return "/car/car";
    }

    /**
     * 通过场站id查询车辆信息
     *
     * @param request
     * @param stationId
     * @return
     * @throws UnsupportedEncodingException
     * @throws UnknownHostException
     */
    @RequestMapping(value = "/getCarsByStationId", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String getCarsByStationId(HttpServletRequest request, Long stationId) throws UnsupportedEncodingException, UnknownHostException {

        List<Car> carList = carService.findCarsByStationId(stationId);

        JSONArray jsonArray = JSONArray.fromObject(carList);

        return jsonArray.toString();
    }


    /**
     * 通过车牌号查询平均装载率信息
     *
     * @param request
     * @param carNumber
     * @return
     * @throws UnsupportedEncodingException
     * @throws UnknownHostException
     */
    @RequestMapping(value = "/getCarAveRateInfo", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String getCarAveRateInfo(HttpServletRequest request, String carNumber) throws UnsupportedEncodingException, UnknownHostException, ParseException {

        //当月数据，31天
        //获取月份
        String thisMonth = DateTool.Date2String(new Date(), "yyyy-MM");
//        String thisMonth = "2018-03";
        //获取年份
        String thisYear = DateTool.Date2String(new Date(), "yyyy");
//        String thisYear = "2018";


        Calendar cal = Calendar.getInstance();
       /* //设置年份
        cal.set(Calendar.YEAR,year);
        //设置月份
        cal.set(Calendar.MONTH, month-1);*/
        //获取某月最大天数
        int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);

        String lDay = String.valueOf(lastDay);

        //当月起止结尾时间
        String mStartTime = thisMonth + "-01 00:00:00";
        String mEndTime = thisMonth + "-" + lDay + " 23:59:59";

        List<Mession> messionList2 = messionDao.findByCarNumber(carNumber);

        List<Mession> messionList = new ArrayList<>();

        for (Mession mession:messionList2)
        {
            if("0".equals(mession.getRate()))
            {

            }
            else
            {
                messionList.add(mession);
            }
        }


        //当月数据集合
        Double[] monthDate = new Double[lastDay];

        //月度信息数据
        for (int m = 1; m < lastDay + 1; m++) {
            Double t = 0.0;

            String day = "";

            if (m < 10) {
                day = "0" + String.valueOf(m);
            } else {
                day = String.valueOf(m);
            }

            int k = 0;
            //遍历添加数据
            for (Mession mession : messionList) {
                if(mession.getIsOver() == 0)
                {
                    continue;
                }
                try
                {
                    if (DateTool.Date2String(mession.getCreateTime(), "yyyy-MM-dd").equals(thisMonth + "-" + day)) {
                        k++;
                        t += Double.parseDouble(mession.getRate());
                    }
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }

            }


            if (k == 0) {
                monthDate[m - 1] = 0.0;
            } else {
                DecimalFormat df=new DecimalFormat(".#");
                String st=df.format(t / k);

                Double ss = Double.parseDouble(st);

                monthDate[m - 1] = ss;
            }


        }


        //当月数据集合
        Double[] yearDate = new Double[12];
        //年度信息数据
        for (int m = 1; m < 13; m++) {
            Double t = 0.0;

            String month = "";

            if (m < 10) {
                month = "0" + String.valueOf(m);
            } else {
                month = String.valueOf(m);
            }

            int k = 0;
            //遍历添加数据
            for (Mession mession : messionList) {
                if(mession.getIsOver() == 0)
                {
                    continue;
                }
                try
                {
                    if (DateTool.Date2String(mession.getCreateTime(), "yyyy-MM").contains(thisYear + "-" + month)) {
                        k++;
                        t += Double.parseDouble(mession.getRate());
                    }
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }


            if (k == 0) {
                yearDate[m - 1] = 0.0;
            } else {
                DecimalFormat df=new DecimalFormat(".#");
                String st=df.format(t / k);

                Double ss = Double.parseDouble(st);
                yearDate[m - 1] = ss;
            }


        }

        JSONObject object = new JSONObject();

        object.put("dataMonth", monthDate);
        object.put("dataYear", yearDate);

        String messionString = "";

        messionString += "<thead class='font-bold'>";
        messionString += "<td>任务单编号</td>";
        messionString += "<td>始发地</td>";
        messionString += "<td>目的地</td>";
        messionString += "<td>装载率</td>";
        messionString += "<td>货物体积</td>";
        messionString += "<td>装车用时</td>";
        messionString += "<td>卸车用时</td>";
        messionString += "</thead>";


       String messionList1 = "";

        String thisMonth11 = DateTool.Date2String(new Date(),"yyyy-MM");

        for (Mession mession : messionList) {
            if(mession.getIsOver() == 0)
            {
                continue;
            }

            String monthTime = DateTool.Date2String(mession.getCreateTime(),"yyyy-MM-dd HH:mm:ss");

            if(monthTime.contains(thisMonth11))
            {
                try
                {
                    Car car = carDao.findCarByCarNumberAndIsDel(carNumber, 0);

                    //计算体积
                    Double tj = (Double.parseDouble(car.getLength()) * Double.parseDouble(car.getWidth()) * Double.parseDouble(car.getHeight()) * Double.parseDouble(mession.getRate())) / 100;

                    DecimalFormat df = new DecimalFormat(".#");
                    String st = df.format(tj);

                    //装车用时
                    String zcdate = RateController.getDistanceTime(DateTool.Date2String(mession.getStartOpenDoorTime(), "yyyy-MM-dd HH:mm:ss"), DateTool.Date2String(mession.getStartCloseDoorTime(), "yyyy-MM-dd HH:mm:ss"));
                    //卸车用时
                    String xcdate = RateController.getDistanceTime(DateTool.Date2String(mession.getEndOpenDoorTime(), "yyyy-MM-dd HH:mm:ss"), DateTool.Date2String(mession.getEndCloseDoorTime(), "yyyy-MM-dd HH:mm:ss"));


                    messionList1 += "<tr>";
                    messionList1 += "<td >" + mession.getMessionNumber() + "</td>";
                    messionList1 += "<td>" + mession.getStartAddress() + "</td>";
                    messionList1 += "<td>" + mession.getEndAddress() + "</td>";
                    DecimalFormat format = new DecimalFormat("0.0");
                    String a = format.format(new BigDecimal(mession.getRate()));

                    messionList1 += "<td>" + a + "%</td>";
                    messionList1 += "<td>";
                    messionList1 += st + "m<sup>2</sup>";
                    messionList1 += "</td>";
                    messionList1 += "<td>" + zcdate + "</td>";
                    messionList1 += "<td>" + xcdate + "</td>";
                    messionList1 += "</tr>";
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }

            try
            {
                Car car = carDao.findCarByCarNumberAndIsDel(carNumber, 0);

                //计算体积
                Double tj = (Double.parseDouble(car.getLength()) * Double.parseDouble(car.getWidth()) * Double.parseDouble(car.getHeight()) * Double.parseDouble(mession.getRate())) / 100;

                DecimalFormat df = new DecimalFormat(".#");
                String st = df.format(tj);

                //装车用时
                String zcdate = RateController.getDistanceTime(DateTool.Date2String(mession.getStartOpenDoorTime(), "yyyy-MM-dd HH:mm:ss"), DateTool.Date2String(mession.getStartCloseDoorTime(), "yyyy-MM-dd HH:mm:ss"));
                //卸车用时
                String xcdate = RateController.getDistanceTime(DateTool.Date2String(mession.getEndOpenDoorTime(), "yyyy-MM-dd HH:mm:ss"), DateTool.Date2String(mession.getEndCloseDoorTime(), "yyyy-MM-dd HH:mm:ss"));


                messionString += "<tr>";
                messionString += "<td >" + mession.getMessionNumber() + "</td>";
                messionString += "<td>" + mession.getStartAddress() + "</td>";
                messionString += "<td>" + mession.getEndAddress() + "</td>";
                DecimalFormat format = new DecimalFormat("0.0");
                String a = format.format(new BigDecimal(mession.getRate()));

                messionString += "<td>" + a + "%</td>";
                messionString += "<td>";
                messionString += st + "m<sup>2</sup>";
                messionString += "</td>";
                messionString += "<td>" + zcdate + "</td>";
                messionString += "<td>" + xcdate + "</td>";
                messionString += "</tr>";
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }

        }

        object.put("messionString", messionString);
        object.put("messionStringMonth", messionList1);

        return object.toString();
    }


    /**
     * 通过车牌号查询表三数据，出车次数
     *
     * @param request
     * @param carNumber
     * @return
     * @throws UnsupportedEncodingException
     * @throws UnknownHostException
     */
    @RequestMapping(value = "/getCarOutNumberDataInfo", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String getCarOutNumberDataInfo(HttpServletRequest request, String carNumber) throws UnsupportedEncodingException, UnknownHostException {

        //当月数据，31天
        //获取月份
        String thisMonth = DateTool.Date2String(new Date(), "yyyy-MM");
//
//        String thisMonth = "2018-03";
        //获取年份
        String thisYear = DateTool.Date2String(new Date(), "yyyy");
//        String thisYear = "2018";


        Calendar cal = Calendar.getInstance();
       /* //设置年份
        cal.set(Calendar.YEAR,year);
        //设置月份
        cal.set(Calendar.MONTH, month-1);*/
        //获取某月最大天数
        int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);

        String lDay = String.valueOf(lastDay);

        //当月起止结尾时间
        String mStartTime = thisMonth + "-01 00:00:00";
        String mEndTime = thisMonth + "-" + lDay + " 23:59:59";

        List<Mession> messionList2 = messionDao.findByCarNumber(carNumber);

        List<Mession> messionList = new ArrayList<>();

        for (Mession mession:messionList2)
        {
            if("0".equals(mession.getRate()))
            {

            }
            else
            {
                messionList.add(mession);
            }
        }


        //当月数据集合
        int[] monthDate = new int[lastDay];

        //月度信息数据
        for (int m = 1; m < lastDay + 1; m++) {
            int t = 0;

            String day = "";

            if (m < 10) {
                day = "0" + String.valueOf(m);
            } else {
                day = String.valueOf(m);
            }

            //遍历添加数据
            for (Mession mession : messionList) {
                if (DateTool.Date2String(mession.getCreateTime(), "yyyy-MM-dd").equals(thisMonth + "-" + day)) {
                    t++;
                }
            }

            monthDate[m - 1] = t;

        }

        //当月数据集合
        int[] yearDate = new int[12];
        //年度信息数据
        for (int m = 1; m < 13; m++) {
            int t = 0;

            String month = "";

            if (m < 10) {
                month = "0" + String.valueOf(m);
            } else {
                month = String.valueOf(m);
            }

            //遍历添加数据
            for (Mession mession : messionList) {
                if (DateTool.Date2String(mession.getCreateTime(), "yyyy-MM").contains(thisYear + "-" + month)) {
                    t++;
                }
            }

            yearDate[m - 1] = t;

        }

        JSONObject object = new JSONObject();

        object.put("dataMonth", monthDate);
        object.put("dataYear", yearDate);

        return object.toString();
    }


    /**
     * 通过车牌号查询报表1数据
     *
     * @param request
     * @param carNumber
     * @return
     * @throws UnsupportedEncodingException
     * @throws UnknownHostException
     */
    @RequestMapping(value = "/getCarDataInfo", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String getCarDataInfo(HttpServletRequest request, String carNumber,String monthYear) throws UnsupportedEncodingException, UnknownHostException, ParseException {

        //需要获取的数据有，查询当年12月份的数据，车辆指定时间端内各个数据信息

        //获取月份
        String thisMonth = DateTool.Date2String(new Date(), "yyyy-MM");
//        String thisMonth = "2018-03";
        //获取年份
        String thisYear = DateTool.Date2String(new Date(), "yyyy");
//        String thisYear = "2018";

        Calendar cal = Calendar.getInstance();
       /* //设置年份
        cal.set(Calendar.YEAR,year);
        //设置月份
        cal.set(Calendar.MONTH, month-1);*/
        //获取某月最大天数
        int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);

        String lDay = String.valueOf(lastDay);

        //当月起止结尾时间
        String mStartTime = thisMonth + "-01 00:00:00";
        String mEndTime = thisMonth + "-" + lDay + " 23:59:59";

        //本年度
        String yStatTime = thisYear + "-01-01 00:00:00";
        String yEndTime = thisYear + "-12-31 23:59:59";

        //开始结束日期
        Date sDate = new Date();
        Date eDate = new Date();

        //总天数
        String days = "0";


        if("0".equals(monthYear))
        {
            //查询月度
            sDate = DateTool.string2Date(mStartTime,"yyyy-MM-dd HH:mm:ss");
            eDate = DateTool.string2Date(mEndTime,"yyyy-MM-dd HH:mm:ss");

            days = gongshiTimePlus(new Date(),DateTool.string2Date(mStartTime,"yyyy-MM-dd HH:mm:ss"));
        }
        else
        {
            sDate = DateTool.string2Date(yStatTime,"yyyy-MM-dd HH:mm:ss");
            eDate = DateTool.string2Date(yEndTime,"yyyy-MM-dd HH:mm:ss");

            days = gongshiTimePlus(new Date(),DateTool.string2Date(yStatTime,"yyyy-MM-dd HH:mm:ss"));
        }

        //查出该车辆所有数据
        List<CarInfoData> carInfoDataList = carInfoDataDao.findByCarNumberAndCreateTimeAfterAndCreateTimeBefore(carNumber,sDate,eDate);

        //当月数据集合
        float[] monthDate = new float[lastDay];

        //月度信息数据
        for (int m = 1; m < lastDay + 1; m++) {
            float t = 0;

            String day = "";

            if (m < 10) {
                day = "0" + String.valueOf(m);
            } else {
                day = String.valueOf(m);
            }

            //遍历添加数据
            for (CarInfoData carInfoData : carInfoDataList) {
                if (carInfoData.getTimeDate().equals(thisMonth + "-" + day)) {
                    t += carInfoData.getOnCarTime();
                    t += carInfoData.getOffCarTime();
                    t += carInfoData.getHeavyTime();
                    t += carInfoData.getEmptyTime();
                }
            }
            DecimalFormat fnum  =   new  DecimalFormat("##0.0");
            monthDate[m - 1] = Float.parseFloat(fnum.format(t));

        }

        //当月数据集合
        float[] yearDate = new float[12];
        //年度信息数据
        for (int m = 1; m < 13; m++) {
            float t = 0;

            String month = "";

            if (m < 10) {
                month = "0" + String.valueOf(m);
            } else {
                month = String.valueOf(m);
            }

            //遍历添加数据
            for (CarInfoData carInfoData : carInfoDataList) {
                if (carInfoData.getTimeDate().contains(thisYear + "-" + month)) {
                    t += carInfoData.getOnCarTime();
                    t += carInfoData.getOffCarTime();
                    t += carInfoData.getHeavyTime();
                    t += carInfoData.getEmptyTime();
                }
            }
            DecimalFormat fnum  =   new  DecimalFormat("##0.0");
            yearDate[m - 1] = Float.parseFloat(fnum.format(t));

        }

        //单车工时
        float singlTime = 0;
        float kongxianTime = 0;

        float zhuangcheTime = 0;
        float xiecheTime = 0;
        float zhongshiTime = 0;
        float kongshiTime = 0;


        for (CarInfoData carInfoData : carInfoDataList) {
            singlTime += carInfoData.getOnCarTime();
            singlTime += carInfoData.getOffCarTime();
            singlTime += carInfoData.getHeavyTime();
            singlTime += carInfoData.getEmptyTime();

            zhongshiTime += carInfoData.getHeavyTime();
            xiecheTime += carInfoData.getOffCarTime();
            zhuangcheTime += carInfoData.getOnCarTime();
            kongshiTime += carInfoData.getEmptyTime();

            kongxianTime += carInfoData.getLeisureTime();
        }

//        int stationId = 0;
        int stationId = carDao.findByCarNumberAndIsDel(carNumber,0).getStationId();

        //获取整个场站全部车辆信息
        /*if(carInfoDataList == null || carInfoDataList.size() == 0)
        {
            stationId = carDao.findCarByCarNumberAndIsDel(carNumber,0).getStationId();
        }
        else
        {
            stationId = carInfoDataList.get(0).getStationId();
        }*/


        List<CarInfoData> carInfoDataList1 = carInfoDataDao.findByStationIdAndCreateTimeAfterAndCreateTimeBefore(stationId,sDate,eDate);

        //单车工时
        float singlTimeC = 0;
        float kongxianTimeC = 0;

        float zhuangcheTimeC = 0;
        float xiecheTimeC = 0;
        float zhongshiTimeC = 0;
        float kongshiTimeC = 0;

        for (CarInfoData carInfoData : carInfoDataList1) {
            zhongshiTimeC += carInfoData.getHeavyTime();
            xiecheTimeC += carInfoData.getOffCarTime();
            zhuangcheTimeC += carInfoData.getOnCarTime();
            kongshiTimeC += carInfoData.getEmptyTime();

            kongxianTimeC += carInfoData.getLeisureTime();
        }


        JSONObject object = new JSONObject();

        DecimalFormat fnum  =   new  DecimalFormat("##0.0");


        List<Car> cars = carDao.findCarByStationIdAndIsDel(stationId,0);

        object.put("zhuangcheTime", Float.parseFloat(fnum.format(zhuangcheTime)));
        object.put("xiecheTime", Float.parseFloat(fnum.format(xiecheTime)));
        object.put("zhongshiTime", Float.parseFloat(fnum.format(zhongshiTime)));
        object.put("kongshiTime", Float.parseFloat(fnum.format(kongshiTime)));

        object.put("zhuangcheTimeC", Float.parseFloat(fnum.format(zhuangcheTimeC))/cars.size());
        object.put("xiecheTimeC", Float.parseFloat(fnum.format(xiecheTimeC))/cars.size());
        object.put("zhongshiTimeC", Float.parseFloat(fnum.format(zhongshiTimeC))/cars.size());
        object.put("kongshiTimeC", Float.parseFloat(fnum.format(kongshiTimeC))/cars.size());


        object.put("dataMonth", monthDate);
        object.put("dataYear", yearDate);
        object.put("singlTime", Float.parseFloat(fnum.format(singlTime)));
        object.put("kongxianTime", Float.parseFloat(fnum.format(kongxianTime)));
        object.put("kongxianTimeC", Float.parseFloat(fnum.format(kongxianTimeC)));

        //工时总天数
        object.put("days",Integer.parseInt(days));


        return object.toString();
    }


    /**
     * 通过clientid获取车辆列表
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     * @throws UnknownHostException
     */
    @RequestMapping(value = "/getCarsByClient", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String getCarsByClient(HttpServletRequest request) throws UnsupportedEncodingException, UnknownHostException {

        int clientId = (int) request.getSession().getAttribute("uid");


        List<Car> cars = carDao.findCarByClientIdAndIsDel(clientId,0);

        if(cars == null || cars.size() == 0)
        {
            User user = userDao.findById(clientId);

            Station station = stationDao.findById(Integer.parseInt(user.getStationId()));

            cars = new ArrayList<>();

            cars = carDao.findCarByStationIdAndIsDel(station.getId(),0);
        }

        String carsString = "";

        for (Car car: cars)
        {
            carsString += "<option>"+car.getCarNumber()+"</option>";
        }


        carsString = "<option>全部车辆</option>" + carsString;


        JSONObject object = new JSONObject();

        object.put("msg", carsString);

        return object.toString();

    }







    /**
     * 通过场站id获取场站车辆入港信息
     *
     * @param request
     * @param stationId
     * @return
     * @throws UnsupportedEncodingException
     * @throws UnknownHostException
     */
    @RequestMapping(value = "/getCarInInfoByStationId", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String getCarInInfoByStationId(HttpServletRequest request, int stationId) throws UnsupportedEncodingException, UnknownHostException {

        List<Car> cars = carDao.findCarByStationIdAndIsDel(stationId,0);

        List<String> carNumbers = new ArrayList<>();
        for (Car car : cars)
        {
            carNumbers.add(car.getCarNumber());
        }

        List<CarInInfo> carInInfos = carInfoDao.findByCarNumberIn(carNumbers);

        String infoString = "";

        infoString += "<thead class='font-bold four-border'>";
        infoString += "<tr>";
        infoString += "<td>车牌号</td>";
        infoString += "<td>状态</td>";
        infoString += "<td>到达场站</td>";
        infoString += "<td>出入港时间</td>";
        infoString += "</tr>";
        infoString += "</thead>";


        String today = DateTool.Date2String(new Date(),"yyyy-MM-dd");
//        String today = "2018-03-29";
        Calendar cal=Calendar.getInstance();
        //System.out.println(Calendar.DATE);//5
        cal.add(Calendar.DATE,-1);
        Date time=cal.getTime();
        System.out.println(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(time));
        String yesToday = new SimpleDateFormat("yyyy-MM-dd").format(time);


        Collections.sort(carInInfos, new Comparator<CarInInfo>() {

            public int compare(CarInInfo o1, CarInInfo o2) {
                // 按照学生的年龄进行升序排列
                if (o1.getCreateTime().after(o2.getCreateTime())) {
                    return -1;
                }
                if (o1.getCreateTime() == o2.getCreateTime()) {
                    return 0;
                }
                return 1;
            }
        });



        for (CarInInfo carInInfo : carInInfos) {

            String timess = DateTool.Date2String(carInInfo.getCreateTime(),"yyyy-MM-dd HH:mm:ss");

            if(timess.contains(today)||timess.contains(yesToday))
            {
                infoString += "<tr>";
                infoString += "<td>";
                infoString += "<span class='txt-limit' title='" + carInInfo.getCarNumber() + "'>" + carInInfo.getCarNumber() + "</span>";
                infoString += "</td>";
                infoString += "<td>";
                String churu = "";

                if(carInInfo.getStatus() == 1)
                {
                    churu = "入港";
                }
                else
                {
                    churu = "出港";
                }


                infoString += "<span class='txt-limit' title='"+churu+"'>" + churu + "</span>";
                infoString += "</td>";
                infoString += "<td><span class='txt-limit' title='" + carInInfo.getStationName() + "'>" + carInInfo.getStationName() + "</span></td>";
                infoString += "<td><span class='txt-limit' title='" + DateTool.Date2String(carInInfo.getCreateTime(),"yyyy-MM-dd HH:mm:ss") + "'>" + DateTool.Date2String(carInInfo.getCreateTime(),"yyyy-MM-dd HH:mm:ss") + "</span></td>";
                infoString += "</tr>";
            }
        }
        JSONObject object = new JSONObject();

        object.put("msg", infoString);

        return object.toString();
    }

    /**
     * 通过场站id获取异常开关门信息
     *
     * @param request
     * @param stationId
     * @return
     * @throws UnsupportedEncodingException
     * @throws UnknownHostException
     */
    @RequestMapping(value = "/getCarOpenInfoByStationId", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String getCarOpenInfoByStationId(HttpServletRequest request, int stationId) throws UnsupportedEncodingException, UnknownHostException {

//        List<CarOpenInfo> carOpenInfos = carOpenInfoDao.findByStationIdOrderByCreateTimeAndMessionNumberDesc(stationId);

        List<CarOpenInfo> carOpenInfos = carOpenInfoDao.findByStationIdOrderByMessionNumberAscCreateTimeAsc(stationId);




        String infoString = "";

        String today = DateTool.Date2String(new Date(),"yyyy-MM-dd");
//        String today = "2018-03-29";
        Calendar cal=Calendar.getInstance();
        //System.out.println(Calendar.DATE);//5
        cal.add(Calendar.DATE,-1);
        Date time=cal.getTime();
        System.out.println(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(time));
        String yesToday = new SimpleDateFormat("yyyy-MM-dd").format(time);



        Collections.sort(carOpenInfos, new Comparator<CarOpenInfo>() {

            public int compare(CarOpenInfo o1, CarOpenInfo o2) {
                // 按照学生的年龄进行升序排列
                if (o1.getCreateTime().after(o2.getCreateTime())) {
                    return -1;
                }
                if (o1.getCreateTime() == o2.getCreateTime()) {
                    return 0;
                }
                return 1;
            }
        });


        for (CarOpenInfo carInInfo : carOpenInfos) {

            String timess = DateTool.Date2String(carInInfo.getCreateTime(),"yyyy-MM-dd HH:mm:ss");

            if(timess.contains(today)||timess.contains(yesToday))
            {
                infoString += "<tr>";
                infoString += "<td  width='20%'>";
                infoString += "<span class='txt-limit' title='" + carInInfo.getCarNumber() + "'>" + carInInfo.getCarNumber() + "</span>";
                infoString += "</td>";
                infoString += "<td width='20%'>";
                if (carInInfo.getOpenStatus() == 1) {
                    infoString += "<span class='txt-limit' title='开门'>开门</span>";
                } else {
                    infoString += "<span class='txt-limit' title='关门'>关门</span>";
                }
                infoString += "</td>";
                infoString += "<td width='30%'>";
                infoString += "<span class='txt-limit' title='" + carInInfo.getAddress() + "'>" + carInInfo.getAddress() + "</span>";
                infoString += "</td>";
                infoString += "<td width='30%'>";
                infoString += "<span class='txt-limit' title='" + DateTool.Date2String(carInInfo.getCreateTime(),"yyyy-MM-dd HH:mm:ss") + "'>" + DateTool.Date2String(carInInfo.getCreateTime(),"yyyy-MM-dd HH:mm:ss") + "</span>";
                infoString += "</td>";
                infoString += "</tr>";

            }


        }
        JSONObject object = new JSONObject();

        object.put("msg", infoString);

        return object.toString();
    }

    /**
     * TODO 分页
     *
     * @param page 页数
     * @param size 条数
     * @return
     * @author dmy
     */
    @GetMapping("getCars")
    public String getCars(@RequestParam(value = "page", defaultValue = "1") Integer page,
                          @RequestParam(value = "size", defaultValue = "10") Integer size,
                          Model model, HttpServletRequest request) {
//        int clientId = (int) request.getSession().getAttribute("uid");
        int clientId = -99;

        try
        {
            clientId = (int) request.getSession().getAttribute("uid");
        }
        catch (Exception e)
        {
            return "car/retry";
        }
        User user = userDao.findOne(clientId);
        PageRequest pageRequest = new PageRequest(page - 1, size);
        Page<Car> carPage = null;
        //超级管理员
        if (user.getType() == 1) {
            carPage = carService.getCarByPageable(pageRequest);
        } else {
            if(user.getType() == 3)
            {
                String stationId = user.getStationId();

                carPage = carService.getCarByPageableByStationId(pageRequest,stationId);
            }
            else
            {
                carPage = carService.getCarByPageable(pageRequest, clientId);
            }
            List<Station> stationByid = (List<Station>) stationService.findStationByClientId(clientId).getData();
            model.addAttribute("AllStation", stationByid);
            model.addAttribute("AllStationSize", stationByid.size());
        }
        List<Car> carList = carPage.getContent();
        model.addAttribute("word", "");
        model.addAttribute("type", "1");
        model.addAttribute("carPage", carPage);
        model.addAttribute("AllCar", carList);
        model.addAttribute("currentPage", page);
        model.addAttribute("size", size);
        model.addAttribute("maxSize", carPage.getTotalPages());
        return "/car/car";
    }

    /**
     * TODO 模糊分页
     *
     * @param page 页数
     * @param size 条数
     * @return
     * @author dmy
     */
    @RequestMapping("choose")
    public String choose(@RequestParam(value = "page", defaultValue = "1") Integer page,
                         @RequestParam(value = "size", defaultValue = "10") Integer size,
                         @RequestParam(value = "word") String word, Model model, HttpServletRequest request) {
        int clientId = (int) request.getSession().getAttribute("uid");
        User user = userDao.findOne(clientId);
//        PageRequest pageRequest = new PageRequest(page - 1, size);
//        Page<Car> carPage = null;
        List<Car> carList = null;
        //超级管理员
        if (user.getType() == 1) {
            carList = (List<Car>) carService.findAllCar().getData();
//            carPage = carService.getCarByPageable(pageRequest);
        } else {
//            carPage = carService.getCarByPageable(pageRequest,clientId);
            carList = (List<Car>) carService.findCarByClientId(clientId).getData();
        }
//        List<Car> carList = carPage.getContent();
        List<Car> carWordList = new ArrayList<>();
        for (Car ca : carList) {
            if (ca.toString().contains(word)) {
                carWordList.add(ca);
            }
        }
        int ceil = (int) Math.ceil(carWordList.size() / 10);
        List<Car> list = WordListUtils.wordListUtils(size, page, carWordList);
        model.addAttribute("word", word);
        model.addAttribute("AllCar", list);
        model.addAttribute("currentPage", page);
        model.addAttribute("size", size);
        model.addAttribute("maxSize", ceil + 1);
        model.addAttribute("type", "2");
        return "/car/car";
    }

    /**
     * TODO ex导出
     *
     * @param
     * @return
     * @author dmy
     */
    @RequestMapping("exout")
    public void exOut(HttpServletResponse response, @RequestParam(value = "word") String word, HttpServletRequest request) {
        int clientId = (int) request.getSession().getAttribute("uid");
        User user = userDao.findOne(clientId);
        List<Car> carList = null;
        List<Car> list = new ArrayList<>();
        if (word == "" && word == null) {
            list = (List<Car>) carService.findCarByClientId(clientId).getData();
        } else {
            if (user.getType() == 1) {
                carList = (List<Car>) carService.findAllCar().getData();
            } else {
                carList = (List<Car>) carService.findCarByClientId(clientId).getData();
            }
            for (Car ca : carList) {
                if (ca.toString().contains(word)) {
                    list.add(ca);
                }
            }
        }
        CarPoi.userPoi(list, response);
    }

    /**
     * TODO ex导入2
     *
     * @param
     * @return
     * @author dmy
     */
    @PostMapping("exoutIn")
    @ResponseBody
    public Result exoutIn(@RequestParam("fileName") MultipartFile file, HttpServletRequest request) {
        int clientId = (int) request.getSession().getAttribute("uid");
        int i = 0;
        List<City> cityList = cityDao.findAll();
        try {
            // 获取文件名
            String fileName = file.getOriginalFilename();
//        logger.info("上传的文件名为：" + fileName);
            // 获取文件的后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            List<Car> list = new ArrayList<>();
            if (suffixName.equals(".xls")) {
                list = ReadExcelCar.readExcel(file, cityList);
            } else if (suffixName.equals(".xlsx")) {
                list = ReadExcelCarCeiling.readExcel(file, cityList);
            } else {
                return Result.build(201, "文件格式不正确");
            }
            for (Car car : list) {
                Car car1 = carDao.findByCarNumberAndIsDel(car.getCarNumber(), CarEnum.ON.getCode());
                if (car1 == null) {
                    Station station = stationDao.findByClientIdAndNameAndIsDel(clientId, car.getStationName(), CarEnum.ON.getCode());
                    if (station != null) {
                        car.setStationId(station.getId());
                        car.setClientId(clientId);
                        car.setCreateTime(new Date());
                        car.setUpdateTime(new Date());
                        carDao.save(car);
                        i = i + 1;
                    }
                }
            }
            return Result.build(200, "导入总条数：" + list.size() + "；" + "成功条数：" + i + "。");
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            return Result.build(500, "系统异常" + "；" + "成功条数：" + i + "。");
        }
    }


    public static String gongshiTimePlus(Date time1, Date time2) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        java.util.Date now = df.parse(DateTool.Date2String(time1, "yyyy-MM-dd HH:mm:ss"));

        java.util.Date date = df.parse(DateTool.Date2String(time2, "yyyy-MM-dd HH:mm:ss"));

        long l = now.getTime() - date.getTime();

        long day = l / (24 * 60 * 60 * 1000);

        long hour = (l / (60 * 60 * 1000) - day * 24);

        long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);

        long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);

        float t = l;

        float ht = t /1000;

        /*DecimalFormat fnum = new DecimalFormat("##0.0");
        String times = fnum.format(ht);*/

//        System.out.println(""+day+"天"+hour+"小时"+min+"分"+s+"秒");

        return String.valueOf(day);
    }
}
